<?php
require_once BASE_PATH.'/db/database.php';
require_once BASE_PATH.'/class/User.class.php';

class Action extends Database {

    public function userLikeAction($uid, $nid, $search_keywords = NULL, $type) {
        if (!isUid($uid) || !isUid($nid)) {
            return json_encode(['status' => '201', 'message' => '无效uid/nid']);
        }

        if ($type != 0 && $type != 1) {         //0:点赞、1：收藏
            return json_encode(['status' => '201', 'message' => '无效的操作类型']);
        }
        $type_name = ($type == 1) ? "收藏" : "点赞"; // 默认设置为“点赞”，如果是1则为“收藏”
        $type_sql_field =  ($type == 1) ? "favorites_count" : "likes_count";
        $action_time = time();

        // 查询用户最后一次操作
        $lastActionSql = "SELECT action_type FROM user_actions 
                      WHERE user_id = '$uid' AND note_id = '$nid' AND action_type = $type
                      ORDER BY action_time DESC LIMIT 1";
        $lastActionResult = $this->getRow($lastActionSql);

        $nuid_sql = "SELECT user_id FROM `note` where note_id = '{$nid}'";
        $nuid = json_decode($this->getRow($nuid_sql),true)['user_id'];

        //get_user_statist 初始化一下用户统计表 给作者
        $uclass = new User();
        $uclass->user_statistics($nuid);

        if (empty($lastActionResult)) {
            $sql = "INSERT INTO user_actions (user_id, note_id, note_user_id, search_keywords, action_type, action_time) 
                VALUES ('$uid', '$nid', '$nuid', '$search_keywords', $type, $action_time)";

            //note_statistics+1
            $update_sql = "UPDATE note_statistics 
            SET {$type_sql_field} = {$type_sql_field} + 1 
            WHERE note_id = '{$nid}'";

            //user_statistics+1 给作者
            $like_add_sql = "UPDATE user_statistics SET likes_received_count = likes_received_count + 1 WHERE user_id = '{$nuid}'";
            $this->query($like_add_sql);


            $this->query($sql);
            $this->query($update_sql);

            return json_encode(['status' => '200', 'message' => $type_name.'成功']);
        }else{
            $deleteSql = "DELETE FROM user_actions 
                      WHERE user_id = '$uid' AND note_id = '$nid' AND action_type = $type";

            $update_sql = "UPDATE note_statistics 
            SET {$type_sql_field} = {$type_sql_field} - 1 
            WHERE note_id = '{$nid}'";

            //user_statistics-1 给作者
            $like_sub_sql = "UPDATE user_statistics SET likes_received_count = likes_received_count - 1 WHERE user_id = '{$nuid}'";
            $this->query($like_sub_sql);

            $this->query($update_sql);
            $this->query($deleteSql);

            return json_encode(['status' => '210', 'message' => $type_name.'已取消']);
        }
    }

    public function getNotifyLike($note_user_id, $page = 1, $limit = 12) {

        if (!isUid($note_user_id)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }

        $offset = ($page - 1) * $limit;

        // 查询action表，并联结用户表和笔记表获取相关信息
        $sql = "SELECT ua.*, u.avatar, u.nickname, u.gender, u.ip, n.title, n.content as ncontent, n.image
            FROM user_actions ua
            LEFT JOIN note n ON ua.note_id = n.note_id
            LEFT JOIN user u ON ua.user_id = u.user_id
            WHERE ua.note_user_id = '{$note_user_id}'
            AND ua.action_type IN (0, 1)
            ORDER BY ua.action_time DESC
            LIMIT $limit OFFSET $offset;";

        $likeaction = $this->getAll($sql);

        return $likeaction;
    }

    public function getNotifyLikeTotal($note_user_id, $limit = 12) {

        if (!isUid($note_user_id)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }

        // 查询action表，并联结用户表和笔记表获取相关信息
        $countSql = "SELECT Count(*) as total
            FROM user_actions ua
            LEFT JOIN note n ON ua.note_id = n.note_id
            LEFT JOIN user u ON ua.user_id = u.user_id
            WHERE ua.note_user_id = '{$note_user_id}'
            AND ua.action_type IN (0, 1)
            LIMIT $limit;";


        $countResult = json_decode($this->getRow($countSql),true);
        $totalCount = $countResult ? $countResult['total'] : 0; // 获取总记录数
        return ceil($totalCount / $limit); // 计算总页码
    }

    public function addViewAction($uid,$nid) {

        if (!isUid($uid)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }

        $nuid_sql = "SELECT user_id FROM `note` where note_id = '{$nid}'";
        $nuid = json_decode($this->getRow($nuid_sql),true)['user_id'];

        $viewor_sql = "SELECT id from user_actions where user_id = '{$uid}' and action_type = 3 and note_id = '{$nid}'";
        $viewor = json_decode($this->getRow($viewor_sql),true)['id'];       //看过没

        if (empty($viewor)) {
            $action_time = time();
            $sql = "INSERT INTO user_actions (user_id, note_id, note_user_id, action_type, action_time) 
                VALUES ('$uid', '$nid', '$nuid', 3, $action_time)";
            $res = $this->query($sql);
            //return $res;
        }else{
            $update_sql = "UPDATE `user_actions` SET `search_view` = '1' WHERE `user_actions`.`id` = {$viewor};";
            $this->query($update_sql);
        }

        return json_encode(['status' => '201', 'message' => '已经增加过观看了！']);

    }

    public function hideViewAction($uid,$nid) {

        if (!isUid($uid)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }
        if($nid){
            if (!isUid($nid)) {
                return json_encode(['status' => '201', 'message' => '无效nid']);
            }
        }

        if ($nid) {
            // 更新指定 ID 的 search_view 为 2
            $sql = "UPDATE `user_actions`
                SET `search_view` = 2
                WHERE `user_id` = '{$uid}' 
                AND `note_id` = '{$nid}'
                AND `action_type` = 3";
        } else {
            // 更新当前用户所有 action_type = '3' 的 search_view 为 2
            $sql = "UPDATE `user_actions`
                SET `search_view` = 2
                WHERE `user_id` = '{$uid}' 
                AND `action_type` = 3";
        }

        $res = $this->query($sql);
        return $res;

    }

    public function userFans($fans_id, $uid) {
        if (!isUid($fans_id) || !isUid($uid) || $uid==$fans_id) {
            return json_encode(['status' => '201', 'message' => '无效uid/fans_id']);
        }

        // 检查粉丝关系是否存在
        $checkQuery = "SELECT id FROM fans WHERE user_id = '$uid' AND fans_id = '$fans_id' LIMIT 1";
        $existingRecord = json_decode($this->getRow($checkQuery),true); // 执行查询


        //get_user_statist 初始化一下用户统计表
        $uclass = new User();
        $uclass->user_statistics($uid);
        $uclass->user_statistics($fans_id);

        if ($existingRecord) {
            // 存在则删除该记录
            $deleteQuery = "DELETE FROM fans WHERE id = {$existingRecord['id']}";
            $deleteResult = $this->query($deleteQuery);
            //user_statistics-1
            $fans_sub_sql = "UPDATE user_statistics SET following_count = following_count - 1 WHERE user_id = '$fans_id'";
            $user_sub_sql = "UPDATE user_statistics SET fans_count = fans_count - 1 WHERE user_id = '$uid'";

            $this->query($fans_sub_sql);
            $this->query($user_sub_sql);

            if ($deleteResult) {
                return json_encode(['status' => '210', 'message' => '已取消关注']);
            } else {
                return json_encode(['status' => '201', 'message' => '取消关注失败']);
            }
        } else {
            // 不存在则插入新记录
            $fans_time = time(); // 获取当前时间戳
            $insertQuery = "INSERT INTO fans (user_id, fans_id, fans_time) VALUES ('{$uid}', '{$fans_id}', $fans_time)";
            $insertResult = $this->query($insertQuery);


            //user_statistics+1
            $fans_add_sql = "UPDATE user_statistics SET following_count = following_count + 1 WHERE user_id = '$fans_id'";
            $user_add_sql = "UPDATE user_statistics SET fans_count = fans_count + 1 WHERE user_id = '$uid'";

            $this->query($fans_add_sql);
            $this->query($user_add_sql);

            if ($insertResult) {
                return json_encode(['status' => '200', 'message' => '关注成功']);
            } else {
                return json_encode(['status' => '201', 'message' => '关注失败']);
            }
        }

    }

    public function userSearch($uid, $keywords) {
        if (!isUid($uid)||!$keywords) {
            return json_encode(['status' => '201', 'message' => '无效uid/关键词']);
        }

        $action_time = time();
        // 过滤关键词，移除多余的空格和特殊字符
        $keywords = addslashes($keywords);
        $keywords = trim($keywords);
        $keywords = htmlspecialchars($keywords, ENT_QUOTES, 'UTF-8');

        $checkSql = "SELECT id 
                 FROM `user_actions` 
                 WHERE `user_id` = '{$uid}' 
                 AND `search_keywords` = '{$keywords}'";
        $checkResult = json_decode($this->getRow($checkSql),true);
        if($checkResult){
            // 如果已存在，则更新 search_view 为 1
            $updateSql = "UPDATE `user_actions` 
                      SET `search_view` = '1' 
                      WHERE `id` = '{$checkResult['id']}'";

            $this->query($updateSql);
            return json_encode(['status' => '210', 'message' => '该用户已经搜索过该关键词']);
        }

        $sql = "INSERT INTO `user_actions` (`id`, `user_id`, `note_id`, `note_user_id`, `search_keywords`, `action_type`, `action_time`, `duration`, `search_view`) VALUES (NULL, '{$uid}', NULL, NULL, '{$keywords}', '2', {$action_time}, NULL, '1');";

        $res = $this->query($sql);
        if($res){
            return json_encode(['status' => '200', 'message' => '搜索行为记录成功']);
        }else{
            return json_encode(['status' => '201', 'message' => '搜索行为记录失败']);
        }
    }

    public function getUserSearchHistory($uid, $page = 1, $perPage = 12)
    {
        if (!isUid($uid)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }
        // 计算分页的偏移量
        $offset = ($page - 1) * $perPage;

        $sql = "SELECT `id`, `search_keywords`, `action_time`
            FROM `user_actions`
            WHERE `user_id` = '{$uid}' 
            AND `action_type` = '2'
            AND `search_view` = '1'
            ORDER BY `action_time` DESC
            LIMIT {$perPage} OFFSET {$offset}";

        $result = $this->getAll($sql);
        if($result){
            return $result;
        }else{
            return json_encode(array());
        }
    }

    public function getSearchHisTotalPages($uid, $perPage = 12)
    {
        if (!isUid($uid)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }

        $countSql = "SELECT COUNT(*) as total
            FROM `user_actions`
            WHERE `user_id` = '{$uid}' 
            AND `action_type` = '2'
            AND `search_view` = '1'";

        $countResult = json_decode($this->getRow($countSql),true);
        $totalCount = $countResult ? $countResult['total'] : 0; // 获取总记录数
        return ceil($totalCount / $perPage); // 计算总页码
    }

    public function getUserViewHistory($uid, $page = 1, $perPage = 12)
    {
        if (!isUid($uid)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }
        // 计算分页的偏移量
        $offset = ($page - 1) * $perPage;

        $sql = "SELECT ua.`id`, ua.`note_id`, ua.`action_time`, n.`title`, n.`content`
        FROM `user_actions` ua
        JOIN `note` n ON ua.`note_id` = n.`note_id`
        WHERE ua.`user_id` = '{$uid}' 
        AND ua.`action_type` = '3'
        AND ua.`search_view` = '1'
        ORDER BY ua.`action_time` DESC
        LIMIT {$perPage} OFFSET {$offset}";


        $result = $this->getAll($sql);
        if($result){
            return $result;
        }else{
            return json_encode(array());
        }
    }

    public function getViewHisTotalPages($uid, $perPage)
    {
        if (!isUid($uid)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }
        // 查询总记录数
        $countSql = "SELECT COUNT(*) as total FROM `user_actions` ua
        JOIN `note` n ON ua.`note_id` = n.`note_id`
        WHERE ua.`user_id` = '{$uid}' 
        AND ua.`action_type` = '3'
        AND ua.`search_view` = '1'
        ORDER BY ua.`action_time` DESC";

        $countResult = json_decode($this->getRow($countSql),true);
        $totalCount = $countResult ? $countResult['total'] : 0; // 获取总记录数
        return ceil($totalCount / $perPage); // 计算总页码
    }

    public function getSearchKeywords($keywords, $page = 1, $perPage = 12)
    {
        if (!$keywords){
            return json_encode(array());
        }
        // 过滤关键词，移除多余的空格和特殊字符
        $keywords = trim($keywords);
        $keywords = htmlspecialchars($keywords, ENT_QUOTES, 'UTF-8');

        // 计算分页的偏移量
        $offset = ($page - 1) * $perPage;

        // 构建 SQL 查询语句
        $sql = "SELECT search_keywords
            FROM (
                SELECT search_keywords, COUNT(*) AS search_count
                FROM user_actions
                WHERE action_type = '2'
                AND search_keywords LIKE '%{$keywords}%'
                GROUP BY search_keywords
            ) AS keyword_counts
            ORDER BY search_count DESC
            LIMIT {$perPage} OFFSET {$offset}";

        // 执行查询
        $result = $this->getAll($sql);

        // 处理结果
        if ($result) {
            return $result;
        } else {
            return json_encode(array());
        }
    }

    public function getTodayHotSearch($page = 1, $perPage = 12)
    {
        // 获取今天的时间戳范围
        $todayStart = strtotime('today');  // 今天开始时间戳
        $todayEnd = strtotime('tomorrow') - 1;  // 今天结束时间戳

        $offset = ($page - 1) * $perPage;

        $sql = "SELECT search_keywords,search_count
            FROM (
                SELECT search_keywords, COUNT(*) AS search_count
                FROM user_actions
                WHERE action_type = '2'
                AND action_time >= {$todayStart} AND action_time <= {$todayEnd}  -- 仅限今天的搜索记录
                GROUP BY search_keywords
            ) AS keyword_counts
            ORDER BY search_count DESC
            LIMIT {$perPage} OFFSET {$offset}";

        $result = $this->getAll($sql);

        if ($result) {
            return $result;
        } else {
            return json_encode(array());
        }
    }

    public function addSearchKey($key, $num)
    {
        // 确保$num是正整数
        if (!is_numeric($num) || $num <= 0 || $num > 10000) {
            return json_encode(['status' => '201', 'message' => '无效num']);
        }

        // 获取当前时间戳
        $currentTime = time();

        $userSql = "SELECT user_id FROM user WHERE u_type = 0 ORDER BY RAND() LIMIT 1";
        $userResult = json_decode($this->getRow($userSql),true)['user_id'];

        // 生成需要插入的数据
        for ($i = 0; $i < $num; $i++) {
            $search_keywords = $key;
            $action_type = 2;
            $action_time = $currentTime;
            $user_id = $userResult;

            $sql = "INSERT INTO user_actions (user_id, search_keywords, action_type, action_time, `search_view`) 
                VALUES ('{$user_id}', '{$search_keywords}', {$action_type}, {$action_time}, 1)";
            //return $sql;
            $this->query($sql);
        }

        return true;
    }


    public function updateAction($id, $action) {
        if (empty($id) || !is_numeric($id)) {
            return json_encode(array('status' => 201, 'message' => 'id error！'));
        }

        // 根据 action 参数执行相应的 SQL 语句
        if ($action == 'hide') {
            $sql = "UPDATE `user_actions` SET `search_view` = '2' WHERE `user_actions`.`id` = {$id};";
        } elseif ($action == 'show') {
            $sql = "UPDATE `user_actions` SET `search_view` = '1' WHERE `user_actions`.`id` = {$id};";
        } elseif ($action == 'delete') {
            $sql = "DELETE FROM `user_actions` WHERE `user_actions`.`id` = {$id};";
        } else {
            return json_encode(array('status' => 201, 'message' => 'type error！'));
        }

        $this->query($sql);
    }

    public function delSearchKey($key) {

        $sql = "DELETE FROM `user_actions` WHERE `user_actions`.`search_keywords` = '{$key}';";

        $this->query($sql);
    }

    public function getBotActions($nid) {
        if (!isUid($nid)) {
            return json_encode(array('status' => 201, 'message' => 'nid error！'));
        }

        // 查询 u_type=0 的所有用户ID
        $sqlAllUsers = "SELECT user_id FROM `user` WHERE u_type = 0";
        $allUsersJson = $this->getAll($sqlAllUsers);
        $allUsers = json_decode($allUsersJson, true); // 解析JSON返回的数据

        // 查询所有执行过 action_type=1 的用户ID (star)
        $sqlAction1Users = "SELECT user_id FROM `user_actions` WHERE action_type = 1 and note_id = '{$nid}' GROUP BY user_id";
        $action1UsersJson = $this->getAll($sqlAction1Users);
        $action1Users = json_decode($action1UsersJson, true); // 解析JSON返回的数据

        // 查询所有执行过 action_type=0 的用户ID (like)
        $sqlAction0Users = "SELECT user_id FROM `user_actions` WHERE action_type = 0 and note_id = '{$nid}' GROUP BY user_id";
        $action0UsersJson = $this->getAll($sqlAction0Users);
        $action0Users = json_decode($action0UsersJson, true); // 解析JSON返回的数据

        // 将执行过 action_type=1 (star) 的 user_id 放入数组
        $action1UserIds = [];
        if ($action1Users) {
            foreach ($action1Users as $row) {
                $action1UserIds[] = $row['user_id'];
            }
        }

        // 将执行过 action_type=0 (like) 的 user_id 放入数组
        $action0UserIds = [];
        if ($action0Users) {
            foreach ($action0Users as $row) {
                $action0UserIds[] = $row['user_id'];
            }
        }

        // 统计用户信息
        $action1Count = 0;
        $action0Count = 0;

        $userData = [
            'like_botid' => [],
            'star_botid' => [],
            'no_like_botid' => [],
            'no_star_botid' => []
        ];

        if ($allUsers) {
            foreach ($allUsers as $row) {
                $userId = $row['user_id'];

                if (in_array($userId, $action1UserIds)) {
                    $action1Count++;
                    $userData['star_botid'][] = $userId;
                } elseif (in_array($userId, $action0UserIds)) {
                    $action0Count++;
                    $userData['like_botid'][] = $userId;
                }
            }

            foreach ($allUsers as $row) {
                $userId = $row['user_id'];

                if (!in_array($userId, $action1UserIds)) {
                    $userData['no_star_botid'][] = $userId;
                }
                if (!in_array($userId, $action0UserIds)) {
                    $userData['no_like_botid'][] = $userId;
                }
            }


        }

        $output = [
            'total_bot' => count($allUsers),
            'no_star_bot_num' => count($userData['no_star_botid']),
            'no_like_bot_num' => count($userData['no_like_botid']),
            'star_bot_num' => $action1Count, // 对应 star
            'like_bot_num' => $action0Count, // 对应 like
            'user_data' => $userData
        ];

        return json_encode($output);

    }


    public function hideSearchView($uid, $id = null)
    {
        if (!isUid($uid)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }
        if ($id !== null && !filter_var($id, FILTER_VALIDATE_INT)) {
            return json_encode(['status' => '201', 'message' => '无效id']);
        }
        if ($id) {
            // 更新指定 ID 的 search_view 为 2
            $sql = "UPDATE `user_actions`
                SET `search_view` = 2
                WHERE `user_id` = '{$uid}' 
                AND `id` = '{$id}'
                AND `action_type` = 2";
        } else {
            // 更新当前用户所有 action_type = '2' 的 search_view 为 2
            $sql = "UPDATE `user_actions`
                SET `search_view` = 2
                WHERE `user_id` = '{$uid}' 
                AND `action_type` = 2";
        }

        $res = $this->query($sql);
        return $res;
    }

    public function getAllAction($page = 1, $limit = 12) {
        $offset = ($page - 1) * $limit;

        // 获取满足条件的评论的总数
        $countSql = "SELECT COUNT(*) as total FROM user_actions";

        $total = json_decode($this->getRow($countSql),true)['total'];

        // 计算总页数
        $totalPages = ceil($total / $limit);

        //$sql = "SELECT * FROM user_actions ORDER BY action_time DESC LIMIT $limit OFFSET $offset";


        $sql = "SELECT ua.*, u.avatar, u.nickname, u.gender, u.ip, n.title
            FROM user_actions ua
            LEFT JOIN note n ON ua.note_id = n.note_id
            LEFT JOIN user u ON ua.user_id = u.user_id
            ORDER BY ua.action_time DESC
            LIMIT $limit OFFSET $offset;";

        $data = json_decode($this->getAll($sql), true);


        // 返回结果，包括评论数据、总页数和总记录数
        return [
            'totalPages' => $totalPages,
            'totalCount' => $total,
            'data' => $data,
        ];
    }






}

?>
